package com.module.overview.ui.widget;

import java.util.TimerTask;

/**
 * 平滑滚动的实现 for HorizontalWheelView
 */
public final class HorizontalSmoothScrollTimerTask extends TimerTask {

    private int realTotalOffset;
    private int realOffset;
    private int offset;
    private final HorizontalWheelView wheelView;

    public HorizontalSmoothScrollTimerTask(HorizontalWheelView wheelView, int offset) {
        this.wheelView = wheelView;
        this.offset = offset;
        realTotalOffset = Integer.MAX_VALUE;
        realOffset = 0;
    }

    @Override
    public final void run() {
        if (realTotalOffset == Integer.MAX_VALUE) {
            realTotalOffset = offset;
        }
        realOffset = (int) ((float) realTotalOffset * 0.1F);
        if (realOffset == 0) {
            if (realTotalOffset < 0) {
                realOffset = -1;
            } else {
                realOffset = 1;
            }
        }
        if (Math.abs(realTotalOffset) <= 1) {
            wheelView.cancelFuture();
            wheelView.getHandler().sendEmptyMessage(HorizontalMessageHandler.WHAT_ITEM_SELECTED);
        } else {
            wheelView.setTotalScrollX(wheelView.getTotalScrollX() + realOffset);
            if (!wheelView.isLoop()) {
                float itemWidth = wheelView.getItemWidth();
                float left = (float) (-wheelView.getInitPosition()) * itemWidth;
                float right = (float) (wheelView.getItemsCount() - 1 - wheelView.getInitPosition()) * itemWidth;
                if (wheelView.getTotalScrollX() <= left || wheelView.getTotalScrollX() >= right) {
                    wheelView.setTotalScrollX(wheelView.getTotalScrollX() - realOffset);
                    wheelView.cancelFuture();
                    wheelView.getHandler().sendEmptyMessage(HorizontalMessageHandler.WHAT_ITEM_SELECTED);
                    return;
                }
            }
            wheelView.getHandler().sendEmptyMessage(HorizontalMessageHandler.WHAT_INVALIDATE_LOOP_VIEW);
            realTotalOffset = realTotalOffset - realOffset;
        }
    }
} 